package gdut.imis.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gdut.imis.Utils.Result;
import gdut.imis.domain.FileType;
import gdut.imis.domain.FileWritePermission;
import gdut.imis.enums.Status;
import gdut.imis.mapper.FileWritePermissionMapper;
import gdut.imis.service.FileWritePermissionService;
import gdut.imis.vo.UserLoginVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author JiaFu
 * @Date 2023/4/7 22:18
 */
@Service
@RequiredArgsConstructor
public class FileWritePermissionServiceImpl extends ServiceImpl<FileWritePermissionMapper, FileWritePermission> implements FileWritePermissionService {
    private final FileWritePermissionMapper fileWritePermissionMapper;

    private static FileType apply(FileType fileType) {
        fileType.setType(StringUtils.uncapitalize(fileType.getType()));
        return fileType;
    }

    /***
     * 获取普通用户（学生/老师）拥有的档案录入权限
     * @return Result
     */
    @Override
    public Result getFileWritePermissions() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginVo userLoginVo = (UserLoginVo) authentication.getPrincipal();
        if (userLoginVo.getIsManager()) {
            return Result.errorWithArgs(Status.FAILED, "管理员不拥有录入权限");
        }
        Long userId = userLoginVo.getUser().getId();
        List<FileType> fileWritePermissionList = fileWritePermissionMapper.getFileWritePermissionsByUserId(userId);
        fileWritePermissionList = fileWritePermissionList.stream()
                .map(FileWritePermissionServiceImpl::apply)
                .collect(Collectors.toList());
        return Result.success(fileWritePermissionList);
    }
}
